package org.jmh.base.interceptor;

import org.jmh.auth.service.IPermissionService;
import org.jmh.base.annotation.JmhPermission;
import org.jmh.base.context.LoginContext;
import org.jmh.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService service;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (Objects.isNull(token)){
            response.getWriter().write("{\"msg\":\"login failed\",\"success\":false}");
            return false;
        }
        Employee employee = LoginContext.loginMap.get(token);
        if(Objects.isNull(employee)){
            response.getWriter().write("{\"msg\":\"login failed\",\"success\":false}");
            return false;
        }
//        1、当前请求的接口是否需要权限
        HandlerMethod method = (HandlerMethod) handler;
        JmhPermission annotation = method.getMethod().getAnnotation(JmhPermission.class);
        if(Objects.isNull(annotation)){
            return true;
        }
//        2、如果需要权限判断用户是否有对应权限
//        2.1、查询用户所拥有的权限->sn=Controller+MethodName
        List<String> userSns = service.selectSnByUserId(employee.getId());
//        2.2、查询接口的权限
        String name = method.getMethod().getName();
        String simpleName = method.getMethod().getDeclaringClass().getSimpleName();
        String sn =simpleName+":"+name;
        if(Objects.isNull(userSns)){
            response.getWriter().write("{\"msg\":\"noPermission\",\"success\":false}");
            return false;
        }
//        2.3、判断用户权限list中是否有接口的权限
        boolean contains = userSns.contains(sn);
        if(!contains){
            response.getWriter().write("{\"msg\":\"noPermission\",\"success\":false}");
            return false;
        }
        return true;
    }
}
